import React from 'react';
import { connect } from 'dva';
import moment from 'moment'
import { Button,Row,Col, Table, Form, Input, Popconfirm, Select,DatePicker ,message} from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
const RangePicker = DatePicker.RangePicker;
import ContractModal from '../../components/contract/ContractModal';
import ContractViewModal from '../../components/contract/ContractViewModal';
import {date2str,replaceStr} from '../../services/common'

function Contract({ dispatch, contract, loading, form }) {
  const columns = [{
    title: '合同号',
    dataIndex: 'no',
    textAlign:'center',
    key: 'no',
    width: 120,
  },{
    title: '名称',
    dataIndex: 'name',
    key: 'name',
    width: 100,
  },{
    title: '类型',
    dataIndex: 'type',
    key: 'type',
    width: 80,
    render: (value, row, index) => {
        return (
            value==1?"买卖合同":value==2?"赠与合同":value==3?"租赁合同":'借用合同'
        )
      }
  },{
    title: '签订日期',
    dataIndex: 'signingDate',
    key: 'signingDate',
    width: 80,
    render: (value, row, index) => {
      return (
        value?new moment(value).format("YYYY-MM-DD"):""
      )
    },
  },{
    title: '生效日期',
    dataIndex: 'effectiveDate',
    key: 'effectiveDate',
    width: 80,
    render: (value, row, index) => {
      return (
        value?new moment(value).format("YYYY-MM-DD"):""
      )
    },
  },{
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 100
  },{
    title: '更新时间',
    dataIndex: 'updateTime',
    key: 'updateTime',
    width: 100
  },
  {
    title: '操作',
    key: 'operation',
    width: 100,
    render: (text, record) => (      
         <span>
         <a onClick={onEditItem.bind(null, record.id_)}>编辑</a>
         <span className="ant-divider" />
         <Popconfirm title="确认删除？" onConfirm={deleteHandler.bind(null, record.id_)}>
         <a>删除</a>
         </Popconfirm>
         <span className="ant-divider" />
         <a onClick={onViewItem.bind(null, record.id_)}>查看</a>
     </span>
    ),
  }
];
  function onSelectChange(selectedRowKeys){    
    dispatch({
      type: 'contract/updateState',
      payload:{selectedRowKeys:selectedRowKeys,buttonVisible:selectedRowKeys==null||selectedRowKeys.length==0?true:false},
    })
  }
  const formItemLayout = {
    wrapperCol: { className: 'wrapper-col' },
  };

  function handleClear(){
    form.resetFields();
    dispatch({
        type: 'contract/queryList',
        payload: { ...getFieldsValue() },
    });
  }

  const onViewItem = (presetId) => {
    dispatch({
      type: 'contract/qryDetailById',
      payload:presetId,
    })
  }

  const onEditItem = (id) => {
    // if(contract.selectedRowKeys==null||contract.selectedRowKeys.length==0){
    //   message.error("请选择一条列表项进行编辑");
    // }else if(contract.selectedRowKeys.length>1){
    //   message.error("最多选择一条列表项进行编辑");
    // }else{
      dispatch({
        type: 'contract/qryById',
        payload: id,
      })
   // }
  }

  function deleteHandler(id) {   
    dispatch({
      type: 'contract/remove',
      payload:id,
      searchObj:contract.searchObj,
    });
  }

  const addHandler = () => {
    dispatch({
      type: 'contract/showModal',
      payload: {
         modalType: 'create',
      },
    })

  }
  const modalDetailProps = {
        item: contract.modalType === 'create' ? {} : contract.currentItem,
        visible: contract.modalVisible,
        type: contract.modalType,
        maskClosable: false,
        dispatch: dispatch,
        confirmLoading: contract.buttonLoading,
        title: contract.modalType === 'create' ? '新建合同' :'编辑合同',
        wrapClassName: 'vertical-center-modal',
        newKey : contract.newKey,
        onOk (data,form) {
          dispatch({
              type: `contract/${contract.modalType}`,
              payload: data,
              searchObj:contract.searchObj,
              form:form,
          })
        },
        onCancel () {
          dispatch({
              type: 'contract/hideModal',
          })
       },
  }

const modalDetailViewProps = {
  item: contract.currentItem,
  visible: contract.modalViewVisible,
  maskClosable: false,
  dispatch: dispatch,
  confirmLoading: contract.buttonLoading,
  title: '查看合同',
  wrapClassName: 'vertical-center-modal',
  newKey : contract.newKey,
  onCancel () {
    dispatch({
        type: 'contract/hideViewModal',
    })
  },
}
  const pagination = {
    current:contract.current,
    pageSize:contract.currentSize,
    total: contract.total,
    showSizeChanger: true,
    showTotal: (total => '共' + contract.total + '条'),
    onShowSizeChange(current, size) {
      dispatch({
        type: 'contract/queryList',
        payload: { ...getFieldsValue(),...{'pageNum':current, 'pageSize':size} },
      });
    },
    onChange(current) {
      let formData=getFieldsValue();
      if(formData.signingDate!=null&&formData.signingDate.length==2){
        formData.signingStartDate=formData.signingDate[0];
        formData.signingEndDate=formData.signingDate[1];
      }
      if(formData.effectiveDate!=null&&formData.effectiveDate.length==2){
        formData.effectiveStartDate=formData.effectiveDate[0];
        formData.effectiveEndDate=formData.effectiveDate[1];
      }
      dispatch({
        type: 'contract/queryList',
        payload: { formData,...{'pageNum':current, 'pageSize':contract.currentSize} },
      });
    },
  };

 const submitHandle = () => {
   let formData=getFieldsValue();
   if(formData.signingDate!=null&&formData.signingDate.length==2){
     formData.signingStartDate=formData.signingDate[0];
     formData.signingEndDate=formData.signingDate[1];
   }
   if(formData.effectiveDate!=null&&formData.effectiveDate.length==2){
     formData.effectiveStartDate=formData.effectiveDate[0];
     formData.effectiveEndDate=formData.effectiveDate[1];
   }
    dispatch({
        type: 'contract/queryList',
        payload: { ...formData },
    });
  }
  const rowSelection = {
       selectedRowKeys:contract.selectedRowKeys,
       onChange: onSelectChange,
     };

  const { getFieldDecorator, getFieldsValue, getFieldValue } = form;
    return (
      <div style={{backgroundColor:'#fff'}}>
        <div style={{minHeight:'100%'}}>
           <div style={{width:'100%',backgroundColor:'#fff',lineHeight:'50px',paddingLeft:'20px',paddingTop:'10px', paddingRight:'20px'}}>
           <Form layout="inline" style={{width:'100%'}}>
               <Row gutter={16}>
                  <Col span={5}>              
                    <FormItem style={{ width: '100%' }}  {...formItemLayout}>
                      {getFieldDecorator('no',{initialValue:''})(
                          <Input type="text" placeholder="请输入合同编号" style={{ width: '100%' }}  />
                      )}
                    </FormItem>
                  </Col>
                  <Col span={5}>
                    <FormItem style={{ width: '100%' }}  {...formItemLayout}>
                      {getFieldDecorator('name',{initialValue:''})(
                          <Input type="text" placeholder="请输入名称" style={{ width: '100%' }} />
                      )}
                    </FormItem>
                  </Col>
                  <Col span={5}>
                    <FormItem style={{ width: '100%' }} {...formItemLayout}>
                        {getFieldDecorator('typeId')(
                        <Select
                            showSearch
                            style={{ width: '100%' }} 
                            placeholder="选择类型"
                            optionFilterProp="children"
                        >
                        <Option value="">全部</Option>
                        <Option value="1">买卖合同</Option>
                        <Option value="2">赠与合同</Option>
                        <Option value="3">租赁合同</Option>
                        <Option value="4">借用合同</Option>
                        </Select>
                        )}
                    </FormItem>
                  </Col>                 
                  <Col span={5}>
                    <FormItem style={{ width: '100%' }} {...formItemLayout}>
                        {getFieldDecorator('signingDate')(
                          <RangePicker placeholder={['签订开始时间', '签订结束时间']} style={{ width: '100%' }}  format="YYYY-MM-DD" />
                        )}
                    </FormItem>
                  </Col>
                  <Col span={4}>
                    <FormItem style={{ width: '100%' }} {...formItemLayout}>
                       {getFieldDecorator('signedName',{initialValue:''})(
                           <Input type="text" placeholder="请输入签订人" style={{ width: '100%' }}  />
                       )}
                    </FormItem>
                  </Col>
                </Row>
                <Row gutter={16}>
                  <Col span={5}>
                    <FormItem style={{ width: '100%' }}  {...formItemLayout}>
                        {getFieldDecorator('effectiveDate')(
                          <RangePicker placeholder={['生效开始时间', '生效结束时间']} style={{ width: '100%' }}  format="YYYY-MM-DD" />
                        )}
                    </FormItem>
                  </Col>
                  <Col span={5}></Col>
                  <Col span={5}></Col>
                  <Col span={2}></Col>
                  <Col span={7} style={{textAlign:'right'}}>
                    <FormItem>
                      <Button type="primary" size='large' onClick={submitHandle} className='ant-search-btn'>查询</Button>
                    </FormItem>
                    <FormItem>
                      <Button size="large" htmlType="reset" onClick={handleClear}>清空</Button>
                    </FormItem>
                    <FormItem>
                    <Button type="primary" size='large' onClick={addHandler}>新增合同</Button>
                </FormItem>
                  </Col>
                </Row>               
                </Form>
            </div>
           
            <div style={{width:'100%',padding:"30px 20px",}}>
                <Table columns={columns} rowKey={record => record.id_} loading={contract.loading}  dataSource={contract.list} pagination={pagination}
                />
            </div>

            {/* <Col span={24}>
            <br/>
            <div style={{width:'100%',padding:"30px 20px",}}>
                <div style={{textAlign:'right'}}>
                  <Button size="large" htmlType="reset" onClick={addHandler}>新建</Button>
                  <Button size="large" htmlType="reset" onClick={onEditItem} disabled={contract.buttonVisible}>编辑</Button>
                  <Popconfirm title="确定要删除吗？" onConfirm={deleteHandler}><Button size="large" htmlType="reset" disabled={contract.buttonVisible}>删除</Button></Popconfirm>
                </div>
                <div>
                <Table columns={columns}
                  rowSelection={rowSelection}
                  rowKey={record => record.id_}
                  loading={contract.loading}
                  dataSource={contract.list}
                  pagination={pagination}
                />
                </div>
            </div>
            </Col>
            </Row> */}
           <ContractModal {...modalDetailProps} />
           <ContractViewModal {...modalDetailViewProps} />
       </div>
     </div>
  );
}

function mapStateToProps(state) {
  return { contract : state.contract,loading:state.loading.models.contract};
}

Contract = Form.create()(Contract);

export default connect(mapStateToProps)(Contract);
